/*********************************************************
 *********************************************************
 ********************                  *******************
 *************                                ************
 *******                  _oo0oo_                  *******
 ***                     o8888888o                     ***
 *                       88" . "88                       *
 *                       (| -_- |)                       *
 *                       0\  =  /0                       *
 *                     ___/`---'\___                     *
 *                   .' \\|     |// '.                   *
 *                  / \\|||  :  |||// \                  *
 *                 / _||||| -:- |||||- \                 *
 *                |   | \\\  -  /// |   |                *
 *                | \_|  ''\---/''  |_/ |                *
 *                \  .-\__  '-'  ___/-. /                *
 *              ___'. .'  /--.--\  `. .'___              *
 *           ."" '<  `.___\_<|>_/___.' >' "".            *
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |          *
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /          *
 *      =====`-.____`.___ \_____/___.-`___.-'=====       *
 *                        `=---='                        *
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      *
 *********__佛祖保佑__永无BUG__验收通过__钞票多多__*********
 *********************************************************/
package org.jbase.oauth.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jbase.oauth.sevice.OauthService;
import org.jbase.oauth.sevice.OauthService.OauthFrom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.qzone.Topic;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.GeneralResultBean;
import com.qq.connect.javabeans.qzone.UserInfoBean;

/**
 * Project: yxt_common <br/>
 * File: OAuth2Controller.java <br/>
 * Class: org.jbase.common.controller.OAuth2Controller <br/>
 * Description: <描述类的功能>. <br/>
 * Copyright: Copyright (c) 2011 <br/>
 * Company: http://www.yxtsoft.com/ <br/>
 * Makedate: 2016年5月26日 下午4:02:53 <br/>
 * 
 * @author liuzhanhong
 * @version 1.0
 * @since 1.0
 */
@Controller("common_oauth2_controller")
@RequestMapping("/oauth")
public class OAuth2Controller {

	@Autowired
	private OauthService oauthService;

	private static final Logger L = LoggerFactory.getLogger(OAuth2Controller.class);

	@RequestMapping("/qq_login")
	public String qq_login(HttpServletRequest request) {
		String url = oauthService.buildAuthorizeURL(OauthFrom.QQ, request);
		return "redirect:" + url;
	}

	@RequestMapping("/qq_afterlogin")
	public String qq_afterlogin(HttpServletRequest request) {

		UserInfo qzoneUserInfo = oauthService.getQzoneUserInfo(request);// new UserInfo(accessToken, openID);
		UserInfoBean userInfoBean = null;
		try {
			userInfoBean = qzoneUserInfo.getUserInfo();
		} catch (QQConnectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Map<String, String> member = new HashMap<String, String>();
		member.put("loginName", userInfoBean.getNickname());
		request.getSession().setAttribute("login_member", member);

		return "redirect:/index";
	}

	@RequestMapping("/qq_shuoshuo")
	public void qq_shuoshuo() {
	}

	@RequestMapping("/qq_shuoshuodo")
	public void qq_shuoshuodo(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html;charset=utf-8");
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		String con = request.getParameter("con");
		L.debug("QQ,con:" + con);
		HttpSession session = request.getSession();
		String accessToken = (String) session.getAttribute("ourpyw_qq_access_token");
		String openID = (String) session.getAttribute("ourpyw_qq_openid");
		L.debug("QQ说说，accessToken:{}，openID:{}", accessToken, openID);
		// 请开发者自行校验获取的con值是否有效
		if (con != "") {
			Topic topic = new Topic(accessToken, openID);
			try {
				GeneralResultBean grb = topic.addTopic(con);
				if (grb.getRet() == 0) {
					response.getWriter()
							.println("<a href=\"http://www.qzone.com\" target=\"_blank\">您的说说已发表成功，请登录Qzone查看</a>");
				} else {
					response.getWriter().println("很遗憾的通知您，发表说说失败！原因： " + grb.getMsg());
				}
			} catch (QQConnectException e) {
				L.debug("QQ说说: 抛异常了？");
			} catch (IOException e) {
				L.debug("QQ说说: IO 抛异常了？");
				e.printStackTrace();
			}
		} else {
			L.debug("QQ说说: 获取到的值为空？");
		}
	}

	@RequestMapping("/qqback")
	public void qqback() {
	}

	@RequestMapping("/wechat_login")
	public String wechat_login(HttpServletRequest request, HttpServletResponse response) {
		String wechat_qrconnect = oauthService.buildWechatAuthorizeURL(request);
		return "redirect:" + wechat_qrconnect;
	}

	@RequestMapping("/wechat_afterlogin")
	public void wechat_afterlogin(HttpServletRequest request, HttpServletResponse response) {
	}

	@RequestMapping("/weibo_login")
	public String weibo_login(HttpServletRequest request, HttpServletResponse response) {
		String url = oauthService.buildSinaWeiboAuthorizeURL();
		L.debug("weibo login:  " + url);
		return "redirect:" + url;
	}

	@RequestMapping("/weibo_afterlogin")
	public void weibo_afterlogin(HttpServletRequest request, HttpServletResponse response) {

		weibo4j.http.SinaWeiboAccessToken weiboAccessToken = oauthService.getWeiboAccessToken(request);
		L.debug("weibo_afterlogin:  " + weiboAccessToken);
		String uid = weiboAccessToken.getUid();
		response.setContentType("text/html; charset=utf-8");

		try {
			PrintWriter out = response.getWriter();
			out.write("user login OK: " + uid);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
